<template>
  <view class="waterfall-flow-container" v-if="!loading || items.length > 0">
    <!-- 下拉刷新 -->
    <view class="refresh-container" v-if="enableRefresh">
      <uni-pull-refresh :show="refreshing" @refresh="onRefresh" :contentdown="{content:'下拉刷新'}" :contentrefresh="{content:'刷新中...'}" :contentup="{content:'释放刷新'}"></uni-pull-refresh>
    </view>
    
    <!-- 瀑布流主体 -->
    <view class="waterfall-layout">
      <!-- 左列 -->
      <view class="column column-left">
        <view 
          v-for="(item, index) in leftItems" 
          :key="getItemKey(item)"
          :class="['waterfall-item', { 'loading': item._loading }]"
          @click="onItemClick(item)"
        >
          <!-- 图片容器 -->
          <view class="image-container">
            <image 
              :src="getImageUrl(item)" 
              mode="aspectFill" 
              class="waterfall-image" 
              :style="{ height: item._imageHeight + 'px' }"
              @load="onImageLoad($event, item)"
              @error="onImageError($event, item)"
            ></image>
            
            <!-- 添加一个默认占位符，当图片加载失败或使用默认高度时显示 -->
            <view v-if="item._imageHeight === 200" class="image-placeholder">
              <uni-icons type="image" size="60" color="#ddd"></uni-icons>
            </view>
            
            <!-- 状态标签 -->
            <view v-if="getItemStatus(item)" :class="['status-tag', `status-${getItemStatus(item)}`]">
              {{ getStatusText(getItemStatus(item)) }}
            </view>
          </view>
          
          <!-- 内容容器 -->
          <view class="content-container">
            <text class="item-title">{{ getItemTitle(item) }}</text>
            
            <view class="rating-container">
                <uni-icons type="star" size="16" :color="themeColor"></uni-icons>
                <text class="rating-text">{{ getItemRating(item) }}</text>
                <text class="favorite-count">({{ getItemFavoriteCount(item) }}人收藏)</text>
              </view>
            
            <view class="location-container">
              <uni-icons type="location" size="16" color="#666"></uni-icons>
              <text class="location-text">{{ getItemAddress(item) }}</text>
            </view>
            
            <view class="facilities-preview" v-if="getItemFacilities(item) && getItemFacilities(item).length > 0">
              <view 
                v-for="(facility, idx) in getPreviewFacilities(getItemFacilities(item))" 
                :key="idx" 
                class="facility-tag"
              >
                {{ facility }}
              </view>
              <text v-if="getItemFacilities(item).length > 3" class="more-facilities">等{{ getItemFacilities(item).length }}项</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 右列 -->
      <view class="column column-right">
        <view 
          v-for="(item, index) in rightItems" 
          :key="getItemKey(item)"
          :class="['waterfall-item', { 'loading': item._loading }]"
          @click="onItemClick(item)"
        >
          <!-- 图片容器 -->
          <view class="image-container">
            <image 
              :src="getImageUrl(item)" 
              mode="aspectFill" 
              class="waterfall-image" 
              :style="{ height: item._imageHeight + 'px' }"
              @load="onImageLoad($event, item)"
              @error="onImageError($event, item)"
            ></image>
            
            <!-- 添加一个默认占位符，当图片加载失败或使用默认高度时显示 -->
            <view v-if="item._imageHeight === 200" class="image-placeholder">
              <uni-icons type="image" size="60" color="#ddd"></uni-icons>
            </view>
            
            <!-- 状态标签 -->
            <view v-if="getItemStatus(item)" :class="['status-tag', `status-${getItemStatus(item)}`]">
              {{ getStatusText(getItemStatus(item)) }}
            </view>
          </view>
          
          <!-- 内容容器 -->
          <view class="content-container">
            <text class="item-title">{{ getItemTitle(item) }}</text>
            
            <view class="rating-container">
                <uni-icons type="star" size="16" :color="themeColor"></uni-icons>
                <text class="rating-text">{{ getItemRating(item) }}</text>
                <text class="favorite-count">({{ getItemFavoriteCount(item) }}人收藏)</text>
              </view>
            
            <view class="location-container">
              <uni-icons type="location" size="16" color="#666"></uni-icons>
              <text class="location-text">{{ getItemAddress(item) }}</text>
            </view>
            
            <view class="facilities-preview" v-if="getItemFacilities(item) && getItemFacilities(item).length > 0">
              <view 
                v-for="(facility, idx) in getPreviewFacilities(getItemFacilities(item))" 
                :key="idx" 
                class="facility-tag"
              >
                {{ facility }}
              </view>
              <text v-if="getItemFacilities(item).length > 3" class="more-facilities">等{{ getItemFacilities(item).length }}项</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 上拉加载更多 -->
    <view class="load-more-container" v-if="enableLoadMore && !loading">
      <uni-load-more :status="loadMoreStatus" :contentdown="{content:'上拉加载更多'}" :contentrefresh="{content:'加载中...'}" :contentnomore="{content:'没有更多数据了'}"></uni-load-more>
    </view>
    
    <!-- 加载中状态 -->
    <view v-if="loading && items.length === 0" class="loading-container">
      <uni-icons type="spinner-cycle" size="40" color="#007aff" animation="spin"></uni-icons>
      <text class="loading-text">加载中...</text>
    </view>
    
    <!-- 空状态 -->
    <view v-if="!loading && items.length === 0" class="empty-container">
      <uni-icons type="image-outline" size="80" color="#ccc"></uni-icons>
      <text class="empty-text">{{ emptyText || '暂无数据' }}</text>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue';
import { onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app';
// 定义组件属性
const props = defineProps({
  items: {
    type: Array,
    default: () => []
  },
  loading: {
    type: Boolean,
    default: false
  },
  enableRefresh: {
    type: Boolean,
    default: true
  },
  enableLoadMore: {
    type: Boolean,
    default: true
  },
  hasMore: {
    type: Boolean,
    default: true
  },
  emptyText: {
    type: String,
    default: '暂无数据'
  },
  imageKey: {
    type: String,
    default: 'images'
  },
  titleKey: {
    type: String,
    default: 'name'
  },
  idKey: {
    type: String,
    default: 'sightId'
  },
  statusKey: {
    type: String,
    default: 'status'
  },
  ratingKey: {
    type: String,
    default: 'rating'
  },
  favoriteCountKey: {
    type: String,
    default: 'favoriteCount'
  },
  addressKey: {
    type: String,
    default: 'address'
  },
  facilitiesKey: {
    type: String,
    default: 'facilities'
  }
});

// 定义事件
const emit = defineEmits(['refresh', 'loadmore', 'itemclick']);

// 响应式数据
const leftItems = ref([]);
const rightItems = ref([]);
const refreshing = ref(false);
const loadMoreStatus = ref('more'); // more, loading, noMore
const columnHeights = ref([0, 0]); // 左右两列的高度
const imageWidth = ref(0); // 图片宽度
const themeColor = ref('#98c3fd'); // 主题色，与theme-style.scss中的$brand-theme-color一致

// 计算属性
const getLeftItems = computed(() => {
  return leftItems.value;
});

const getRightItems = computed(() => {
  return rightItems.value;
});

// 生命周期钩子
onMounted(() => {
  // 计算图片宽度
  calculateImageWidth();
  // 监听窗口大小变化
  uni.onWindowResize(calculateImageWidth);
  // 初始化瀑布流
  initWaterfall();
  
  // 调试：输出props数据
  console.log('Waterfall Flow Props:', {
    items: props.items,
    loading: props.loading,
    hasMore: props.hasMore,
    // 其他props也可以根据需要添加
  });
});

onUnmounted(() => {
  // 移除窗口大小变化监听
  uni.offWindowResize(calculateImageWidth);
});

// 监听下拉刷新和上拉加载
onPullDownRefresh(() => {
  if (props.enableRefresh && !refreshing.value) {
    onRefresh();
  } else {
    uni.stopPullDownRefresh();
  }
});

onReachBottom(() => {
  if (props.enableLoadMore && props.hasMore && loadMoreStatus.value === 'more') {
    onLoadMore();
  }
});

// 方法
const calculateImageWidth = () => {
  // 获取窗口宽度，减去左右边距和中间间距
  const sysInfo = uni.getSystemInfoSync();
  const windowWidth = sysInfo.windowWidth;
  // 两列布局，每列宽度 = (窗口宽度 - 容器padding - 列间距) / 2
  imageWidth.value = (windowWidth - 40 - 20) / 2; // 40是容器左右padding各20，20是列间距
};

const initWaterfall = () => {
  // 重置数据
  leftItems.value = [];
  rightItems.value = [];
  columnHeights.value = [0, 0];
  
  // 处理初始数据
  processItems(props.items);
};

const processItems = (items) => {
  console.log('Processing items:', { itemCount: items ? items.length : 0 });
  
  if (!items || items.length === 0) {
    console.log('No items to process');
    return;
  }
  
  try {
    // 给每个item添加加载状态和默认图片高度
    const itemsWithState = items.map(item => ({
      ...item,
      _loading: true,
      _imageHeight: 200, // 设置默认高度，避免长时间显示空白
    }));
    
    console.log('Items with state added');
    
    // 初始排序：按预估高度（这里使用id作为简单排序）
    // 实际应用中可以使用其他逻辑，比如根据标题长度预估
    const sortedItems = [...itemsWithState].sort((a, b) => {
      return (a[props.idKey] || 0) - (b[props.idKey] || 0);
    });
    
    console.log('Items sorted');
    
    // 分配到左右两列
    sortedItems.forEach((item, index) => {
      const columnIndex = index % 2;
      if (columnIndex === 0) {
        leftItems.value.push(item);
      } else {
        rightItems.value.push(item);
      }
    });
    
    console.log('Items distributed to columns:', { 
      leftCount: leftItems.value.length, 
      rightCount: rightItems.value.length 
    });
  } catch (error) {
    console.error('Error processing items:', error);
  }
};

// 图片加载完成后重新计算布局
const onImageLoad = (event, item) => {
  console.log('Image loaded successfully:', {
    itemId: item[props.idKey],
    imageUrl: getImageUrl(item),
    dimensions: { width: event.detail.width, height: event.detail.height }
  });
  
  // 标记图片加载完成
  item._loading = false;
  
  // 计算图片高度，保持宽高比
  const { width, height } = event.detail;
  const calculatedHeight = (imageWidth.value * height) / width;
  item._imageHeight = calculatedHeight;
  
  // 重新计算布局
  reflowLayout();
};

const onImageError = (event, item) => {
  console.error('Image failed to load:', {
    itemId: item[props.idKey],
    imageUrl: getImageUrl(item),
    error: event
  });
  
  // 图片加载失败，使用默认高度
  item._loading = false;
  item._imageHeight = 200; // 默认高度
  
  // 重新计算布局
  reflowLayout();
};

const reflowLayout = () => {
  nextTick(() => {
    // 计算当前左右列的高度
    let leftHeight = 0;
    let rightHeight = 0;
    
    leftItems.value.forEach(item => {
      leftHeight += item._imageHeight + 200; // 图片高度 + 内容估计高度
    });
    
    rightItems.value.forEach(item => {
      rightHeight += item._imageHeight + 200; // 图片高度 + 内容估计高度
    });
    
    columnHeights.value = [leftHeight, rightHeight];
    
    // 如果高度差过大，可以重新排序
    const heightDiff = Math.abs(leftHeight - rightHeight);
    if (heightDiff > 300) { // 如果高度差超过300px
      rebalanceColumns();
    }
  });
};

const rebalanceColumns = () => {
  // 合并所有项
  const allItems = [...leftItems.value, ...rightItems.value];
  
  // 按图片高度排序（矮的在前）
  const sortedItems = [...allItems].sort((a, b) => {
    return a._imageHeight - b._imageHeight;
  });
  
  // 重置列
  leftItems.value = [];
  rightItems.value = [];
  columnHeights.value = [0, 0];
  
  // 重新分配，优先放入较矮的列
  sortedItems.forEach(item => {
    const minHeightIndex = columnHeights.value[0] <= columnHeights.value[1] ? 0 : 1;
    
    if (minHeightIndex === 0) {
      leftItems.value.push(item);
      columnHeights.value[0] += item._imageHeight + 200; // 图片高度 + 内容估计高度
    } else {
      rightItems.value.push(item);
      columnHeights.value[1] += item._imageHeight + 200; // 图片高度 + 内容估计高度
    }
  });
};

// 刷新处理
const onRefresh = async () => {
  refreshing.value = true;
  emit('refresh');
  
  // 模拟刷新完成
  setTimeout(() => {
    refreshing.value = false;
    uni.stopPullDownRefresh();
  }, 1500);
};

// 加载更多处理
const onLoadMore = () => {
  if (!props.hasMore) {
    loadMoreStatus.value = 'noMore';
    return;
  }
  
  loadMoreStatus.value = 'loading';
  emit('loadmore');
  
  // 模拟加载完成
  setTimeout(() => {
    if (!props.hasMore) {
      loadMoreStatus.value = 'noMore';
    } else {
      loadMoreStatus.value = 'more';
    }
  }, 1500);
};

// 点击项处理
const onItemClick = (item) => {
  emit('itemclick', item);
};

// 获取项目属性的通用方法
const getItemKey = (item) => {
  return item[props.idKey] || Math.random().toString(36).substr(2, 9);
};

const getItemTitle = (item) => {
  return item[props.titleKey] || '未知标题';
};

const getItemStatus = (item) => {
  return item[props.statusKey];
};

const getStatusText = (status) => {
  const textMap = {
    'open': '营业中',
    'closed': '已关闭',
    'maintenance': '维护中'
  };
  return textMap[status] || '';
};

const getItemRating = (item) => {
  return item[props.ratingKey] || '0.0';
};

const getItemFavoriteCount = (item) => {
  return item[props.favoriteCountKey] || 0;
};

const getItemAddress = (item) => {
  return item[props.addressKey] || '未知地址';
};

const getItemFacilities = (item) => {
  return item[props.facilitiesKey] || [];
};

// 清理图片URL
const getImageUrl = (item) => {
  // 调试：输出图片处理过程
  console.log('Processing image URL:', {
    item,
    imageKey: props.imageKey,
    rawImages: item ? item[props.imageKey] : undefined
  });
  
  // 确保item是对象且存在
  if (!item || typeof item !== 'object') {
    console.warn('Invalid item provided to getImageUrl');
    return '';
  }
  
  try {
    // 获取图片数组，确保是数组类型
    const images = Array.isArray(item[props.imageKey]) ? item[props.imageKey] : [];
    
    // 只使用数组的第一个图片
    let firstImage = images[0] || '';
    
    // 确保是字符串类型
    firstImage = String(firstImage);
    
    // 增强的URL清理逻辑：
    // 1. 移除所有反引号
    // 2. 移除前后空格
    // 3. 移除URL中间可能出现的多余空格
    const cleanedUrl = firstImage
      .replace(/[`]/g, '') // 移除所有反引号
      .trim() // 移除前后空格
      .replace(/\s+/g, ''); // 移除所有空格
    
    // 调试：输出最终处理后的URL
    console.log('Final image URL:', cleanedUrl);
    
    return cleanedUrl;
  } catch (error) {
    console.error('Error processing image URL:', error);
    return '';
  }
};

// 获取设施预览（最多显示3个）
const getPreviewFacilities = (facilities) => {
  if (!facilities || facilities.length === 0) {
    return [];
  }
  return facilities.slice(0, 3);
};

// 初始化加载状态
const initializeLoadingState = (items) => {
  if (!items || !Array.isArray(items)) return;
  
  items.forEach(item => {
    // 确保每个item都有初始状态
    item._loading = false; // 设为false避免一直显示加载中
    item._imageHeight = 200; // 设置默认高度
  });
};

// 监听items变化，重新布局
watch(() => props.items, (newItems) => {
  console.log('Items changed:', { hasNewItems: !!newItems, count: newItems ? newItems.length : 0 });
  
  if (newItems) {
    // 初始化所有item的加载状态
    initializeLoadingState(newItems);
    
    // 如果是新加载的数据，追加到现有列表
    if (newItems.length > leftItems.value.length + rightItems.value.length) {
      const addedItems = newItems.slice(leftItems.value.length + rightItems.value.length);
      processItems(addedItems);
    } else {
      // 否则重新初始化
      initWaterfall();
    }
  }
});

// 监听hasMore变化
watch(() => props.hasMore, (hasMore) => {
  if (!hasMore) {
    loadMoreStatus.value = 'noMore';
  }
});
</script>

<style lang="scss" scoped>
// 导入主题样式
@import '../../common/styles/theme-style.scss';

// 定义CSS变量
:root {
  --brand-color: $brand-theme-color;
}

.waterfall-flow-container {
  padding: 20rpx;
}

.refresh-container {
  margin-bottom: 20rpx;
}

.waterfall-layout {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.column {
  width: calc(50% - 10rpx);
}

.waterfall-item {
  background-color: white;
  border-radius: 16rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
  overflow: hidden;
  transition: transform 0.2s;
}

.waterfall-item:active {
  transform: scale(0.98);
}

/* Loading placeholder style removed */

.image-container {
  position: relative;
  width: 100%;
  overflow: hidden;
}

.image-placeholder {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
}

.waterfall-image {
  width: 100%;
  transition: transform 0.3s;
}

.waterfall-image:active {
  transform: scale(1.05);
}

.status-tag {
  position: absolute;
  top: 20rpx;
  left: 20rpx;
  padding: 8rpx 20rpx;
  border-radius: 20rpx;
  color: white;
  font-size: 24rpx;
  font-weight: bold;
}

.status-open {
  background-color: $brand-theme-color;
}

.status-closed {
  background-color: #E64340;
}

.status-maintenance {
  background-color: #FF9500;
}

.content-container {
  padding: 24rpx;
}

.item-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 12rpx;
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  word-break: break-all;
}

.rating-container {
  display: flex;
  align-items: center;
  margin-bottom: 8rpx;
}

.rating-container .uni-icons {
  color: $brand-theme-color !important;
}

.rating-text {
  margin-left: 8rpx;
  font-size: 26rpx;
  color: #333;
  font-weight: bold;
}

.favorite-count {
  margin-left: 8rpx;
  font-size: 22rpx;
  color: #999;
}

.location-container {
  display: flex;
  align-items: center;
  margin-bottom: 12rpx;
}

.location-text {
  margin-left: 8rpx;
  font-size: 24rpx;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
}

.facilities-preview {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 12rpx;
}

.facility-tag {
  background-color: #f0f9ff;
  color: $brand-theme-color;
  font-size: 20rpx;
  padding: 6rpx 12rpx;
  border-radius: 16rpx;
}

.more-facilities {
  color: #999;
  font-size: 20rpx;
  margin-left: 8rpx;
}

.load-more-container {
  padding: 30rpx 0;
}

.loading-container,
.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 60vh;
}

.loading-text,
.empty-text {
  margin-top: 30rpx;
  color: #999;
  font-size: 32rpx;
}

/* 适配H5和小程序 */
@media screen and (min-width: 768px) {
  .waterfall-item {
    box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.15);
  }
}

/* 解决小程序中的一些兼容性问题 */
@supports (padding-bottom: env(safe-area-inset-bottom)) {
  .waterfall-flow-container {
    padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  }
}
</style>